<?php
/**
 * User: hufeng
 * Date: 2016/12/21
 * Desc: excel处理
 */
namespace App\Common\Util;

class Excel{
    //解析xls文件
    function parseXls($file){
        $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        if(!$objReader->canRead($file)){
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        }
        $objPHPExcel = $objReader->load($file,$encode='utf-8');
        /**读取excel文件中的第一个工作表*/
        $currentSheet = $objPHPExcel->getSheet(0);
        /**取得最大的列号*/
        $allColumn = $currentSheet->getHighestColumn();

        /**取得一共有多少行*/
        $allRow = $currentSheet->getHighestRow();
        /**从第二行开始输出，因为excel表中第一行为列名*/
        $res = [];
        for($currentRow = 2;$currentRow <= $allRow;$currentRow++){
            /**从第A列开始输出*/
            for($currentColumn= 'A';$currentColumn<= $allColumn; $currentColumn++){
                $val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue();/**ord()将字符转为十进制数*/
                $res[$currentColumn][$currentRow] = $this->characet($val);
            }
        }
        return $res;
    }

    function characet($data){
        if( !empty($data) ){
            $fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5')) ;
            if( $fileType != 'UTF-8'){
                $data = mb_convert_encoding($data ,'utf-8' , $fileType);
            }
        }
        return $data;
    }
}